package com.yisin.commun.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

import com.yinsin.other.LogHelper;
import com.yisin.commun.modal.Client;

public class TcpServerSocket extends Thread {
    private static final LogHelper logger = LogHelper.getLogger(TcpServerSocket.class);
    private ServerSocket server;
    private IMessageHandler handle;
    private int PORT = 10000;
    private static int status = 0;
    
    private final static class TcpServerSocketHandle{
    	private static TcpServerSocket TSS = new TcpServerSocket();
    }
    
    private TcpServerSocket(){}

    public static TcpServerSocket getInstance() {
        return TcpServerSocketHandle.TSS;
    }

    public void startServer(int port, IMessageHandler handle) {
        if (status == 0) {
            this.PORT = port;
            this.handle = handle;
            start();
        }
    }

    public void run() {
        try {
            if (this.PORT > 0) {
                this.server = new ServerSocket(this.PORT);
                logger.info("Yisin Communication # TCP Socket Server Started! POST = " + this.PORT);
                status = 1;
                String uid = "";
                while (true) {
                    Socket soc = this.server.accept();
                    logger.debug("Client Access to the... ip " + soc.getRemoteSocketAddress().toString());
                    if (this.handle != null) {
                        Client client = new Client(soc);
                        client.setSid(soc.getRemoteSocketAddress().toString());
                        uid = UUID.randomUUID().toString();
                        client.setUuid(uid.replaceAll("-", ""));
                        this.handle.onOpen(client);
                        new TcpServerThread(client, soc, this.handle).start();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private class _TcpServerSocket {
        
    }
}